package com.linh.rmi.server;

import java.lang.reflect.Proxy;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.linh.rmi.common.InvocationDelegate;
import com.linh.rmi.common.ServerInvocationHandler;

public class ObjectRegistration {

	private static final Logger LOG = LoggerFactory
			.getLogger(ObjectRegistration.class);
	private static int port;
	private static Registry serverRegistry;

	public static void init(int rmiPort) throws RemoteException {
		port = rmiPort;
		LOG.info("Create RMI registry at " + port);
		serverRegistry = LocateRegistry.createRegistry(port);
	}

	public static void register(String name, InvocationDelegate object)
			throws RemoteException {
		// create a stub
		InvocationDelegate delegate = (InvocationDelegate) UnicastRemoteObject
				.exportObject(object, port);
		ServerInvocationHandler invocationHandler = new ServerInvocationHandler(
				delegate);
		// create a proxy
		Object proxy = Proxy.newProxyInstance(object.getClass()
				.getClassLoader(), object.getClass().getInterfaces(),
				invocationHandler);
		String objectName = object.getClass().getName();
		LOG.info("Registering object " + objectName + " ...");
		serverRegistry.rebind(name, (Remote) proxy);
		LOG.info("Succeed in registering object " + objectName);
	}

}
